﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
using System.Web.Script.Serialization;
using System.Data.Linq;
using System.Configuration;
using System.Data;

namespace IGIS
{
    /// <summary>
    /// Summary description for igisHandler
    /// </summary>
    public class igisHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
           /* context.Response.ContentType = "text/plain";
            context.Response.Write("Hello World");*/

            string result = string.Empty;
            string request = string.Empty;
            string userName = "g";
            try
            {
                using (StreamReader reader = new StreamReader(context.Request.InputStream))
                {
                    request = reader.ReadToEnd();
                }
                switch (context.Request.QueryString["action"])
                {
                    case "GetPolygonSearch":
                        result = GetPolygonSearch(JsonToObject<polygonsearch>(request));
                        break;
                    case "GetAutoCompletefltr":
                        result = GetAutoCompletefltr(JsonToObject<polygonsearch>(request));
                        break;
                    case "saveProcess":
                        //  result = GeneralHelper.ObjectToJson(Bl.SaveProcess(userName, GeneralHelper.JsonToObject<Process>(request)));
                        break;
                }
            }
            catch (Exception ex)
            {
                //result = GeneralHelper.ObjectToJson( new ReqRes<string> { Message = ex.ToString() } );
            }
            context.Response.Write(result);
        }
        public string GetJson(DataTable dt)
        {
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new

            System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<string, object>> rows =
              new List<Dictionary<string, object>>();
            Dictionary<string, object> row = null;

            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName.Trim(), dr[col]);
                }
                rows.Add(row);
            }
            return serializer.Serialize(rows);
        }
        public static T JsonToObject<T>(string request){
            T myDeserializedObjList = (T)Newtonsoft.Json.JsonConvert.DeserializeObject(request, typeof(T));
            return myDeserializedObjList;
        }
        protected static string ObjectToJson(Object obj)
        {
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = int.MaxValue };
            var json = serializer.Serialize(obj);
            return json;
        }
        public string GetPolygonSearch(polygonsearch _objtosearch)
        {

            using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["IGISConnectionString"].ConnectionString))
            {
                bool usewhere = false;
                string sqlquery = "select * from " + _objtosearch.SelectedDrpSearchBy.TableName;
                if (!string.IsNullOrEmpty(_objtosearch.SelectedFilter1) && !string.IsNullOrEmpty(_objtosearch.SelectedFilter1val))
                {
                    sqlquery += " where " + _objtosearch.SelectedFilter1 + "='" + _objtosearch.SelectedFilter1val + "'";
                    usewhere = true;
                }
                if (!string.IsNullOrEmpty(_objtosearch.SelectedFilter2) && !string.IsNullOrEmpty(_objtosearch.SelectedFilter2val))
                {
                 
                    if (usewhere)
                    {
                        sqlquery += " or " + _objtosearch.SelectedFilter2 + "='" + _objtosearch.SelectedFilter2val + "'";
                    }
                    else {
                        sqlquery += " where " + _objtosearch.SelectedFilter2 + "='" + _objtosearch.SelectedFilter2val + "'";
                        usewhere = true;
                    }
                }
                if (!string.IsNullOrEmpty(_objtosearch.SelectedFilter3) && !string.IsNullOrEmpty(_objtosearch.SelectedFilter3val))
                {
                    if (usewhere)
                    {
                        sqlquery += " or " + _objtosearch.SelectedFilter3 + "='" + _objtosearch.SelectedFilter3val + "'";
                    }
                    else {
                        sqlquery += " where " + _objtosearch.SelectedFilter3 + "='" + _objtosearch.SelectedFilter3val + "'";
                    }
                }

                var cmd = conn.CreateCommand();
                cmd.CommandText = sqlquery;
                
                conn.Open();
                IDataReader dr= cmd.ExecuteReader();

                    DataTable tb = new DataTable();
                 tb.Load(dr);
                 return GetJson(tb);
            }
            
            
            /*if (!_customers.Update(TBL_Project))
                throw new HttpResponseException(HttpStatusCode.NotFound);*/

            //   return customer;



        }
        public string GetAutoCompletefltr(polygonsearch _objtosearch)
        {

            using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["IGISConnectionString"].ConnectionString))
            {
                string filterfield="";
                string sqlquery = string.Empty;
                if (!string.IsNullOrEmpty(_objtosearch.SelectedFilter1) && !string.IsNullOrEmpty(_objtosearch.SelectedFilter1val))
                {   filterfield=_objtosearch.SelectedFilter1;
                     sqlquery = "select " + _objtosearch.SelectedFilter1 + " from " + _objtosearch.SelectedDrpSearchBy.TableName;
                    sqlquery += " where " + _objtosearch.SelectedFilter1 + " like '%" + _objtosearch.SelectedFilter1val + "%'";
                }
                if (!string.IsNullOrEmpty(_objtosearch.SelectedFilter2) && !string.IsNullOrEmpty(_objtosearch.SelectedFilter2val))
                {
                     filterfield=_objtosearch.SelectedFilter2;
                     sqlquery = "select " + _objtosearch.SelectedFilter2 + " from " + _objtosearch.SelectedDrpSearchBy.TableName;
                    sqlquery += " where " + _objtosearch.SelectedFilter2 + " like '%" + _objtosearch.SelectedFilter2val + "%'";
                }
                if (!string.IsNullOrEmpty(_objtosearch.SelectedFilter3) && !string.IsNullOrEmpty(_objtosearch.SelectedFilter3val))
                {
                     filterfield=_objtosearch.SelectedFilter3;
                     sqlquery = "select " + _objtosearch.SelectedFilter3 + " from " + _objtosearch.SelectedDrpSearchBy.TableName;
                    sqlquery += " where "  + _objtosearch.SelectedFilter3 + " like '%" + _objtosearch.SelectedFilter3val + "%'";
                }

                var cmd = conn.CreateCommand();
                cmd.CommandText = sqlquery;

                conn.Open();
                IDataReader dr = cmd.ExecuteReader();

                DataTable tb = new DataTable();
               
                tb.Load(dr);
                string s = "[";
                int i=0;
                foreach (DataRow item in tb.Rows)
                {
                    if (i == 0)
                    {
                        s += "\"" + item[filterfield] + "\"";
                    }
                    else
                    {
                        s += ",\"" + item[filterfield] + "\"";
                    }
                    i++;
                }
                s += "]";
                return s;
            }


            /*if (!_customers.Update(TBL_Project))
                throw new HttpResponseException(HttpStatusCode.NotFound);*/

            //   return customer;



        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
   

    
     [DataContract]
    public class SelectedDrpSearchBy
    {
         [DataMember(EmitDefaultValue = false)]
         public string Filter1Fields { get; set; }
         [DataMember(EmitDefaultValue = false)]
         public string Filter2Fields { get; set; }
         [DataMember(EmitDefaultValue = false)]
         public string Filter3Fields { get; set; }
         [DataMember(EmitDefaultValue = false)]
         public string SelectedFilter1 { get; set; }


     }
     [DataContract]
    public class polygonsearch
    {
        [DataMember(EmitDefaultValue = false)]
        public TBL_SearchConfigurator SelectedDrpSearchBy { get; set; }
        [DataMember(EmitDefaultValue = false)]
        public string SelectedFilter1 { get; set; }
        [DataMember(EmitDefaultValue = false)]
        public string  SelectedFilter2 { get; set; }
        [DataMember(EmitDefaultValue = false)]
         public string  SelectedFilter3 { get; set; }
           
         [DataMember(EmitDefaultValue = false)]
         public string  SelectedFilter1val { get; set; }
           [DataMember(EmitDefaultValue = false)]
         public string  SelectedFilter2val { get; set; }
          [DataMember(EmitDefaultValue = false)]
         public string  SelectedFilter3val { get; set; }
         

       
    }
}